package com.zegome.game;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import mobi.vserv.android.ads.AdLoadCallback;
import mobi.vserv.android.ads.AdOrientation;
import mobi.vserv.android.ads.ViewNotEmptyException;
import mobi.vserv.android.ads.VservAd;
import mobi.vserv.android.ads.VservController;
import mobi.vserv.android.ads.VservManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestBatch;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.widget.WebDialog;
import com.zegome.facebook.CustomLogin;
import com.zegome.facebook.IFacebookEventListener;
import com.zegome.facebook.IFacebookProcessorListener;
import com.zegome.game.main.AndroidGameController;
import com.zegome.game.main.ZegomeActivity;
import com.zegome.game.me.AndroidHelper;
import com.zegome.game.oanquan.GameCenter;
import com.zegome.game.oanquan.OAnQuanController;
import com.zegome.game.oanquan.R;

public class MainActivity extends ZegomeActivity implements IFacebookEventListener{
	private static final String TAG = MainActivity.class.getName();
	private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
	private static final int ID = 2;
	
//	private List<String> PUBLISH_PERMISSIONS = Arrays.asList("publish_stream");
	private List<String> PERMISSIONS = Arrays.asList("publish_actions");
	private String mRequestId = null;
	
	private CustomLogin mCustomLogin;
	private StatusCallback mCallback = new StatusCallback() {
		
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			if (isPause) return;
			onSessionStateChange(session, state, exception);
		}
	};
	
	private UiLifecycleHelper mUiLifecycleHelper;

	private ProgressDialog progressDialog;
	
	private IFacebookProcessorListener mFBProcessorListener;

	private int mAction = -1;
	
	private boolean isPause = false;
	static final boolean UPLOAD_IMAGE = false;
	private boolean pendingPublishReauthorization = false;
	
	/*
	 * VservSea
	 */
//	private RelativeLayout adView;
//	private VservAd adObject;
//	private Context context;
//	private VservController controller;
//	private VservManager manager;
//	private static final String BILLBOARD_ZONE = "8063";
//	private static final String BANNER_ZONE = "20846";
	
	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================
	@Override
	public void onComplete(final Bundle savedInstanceState) {
//		try {
//		    PackageInfo info = MainActivity.this.getPackageManager().getPackageInfo(
//		          "com.zegome.game", PackageManager.GET_SIGNATURES);
//		    for (Signature signature : info.signatures) 
//		        {
//		           MessageDigest md = MessageDigest.getInstance("SHA");
//		           md.update(signature.toByteArray());
//		           Log.d("KeyHash:","key hash: " + Base64.encodeToString(md.digest(), Base64.DEFAULT));
//		        }
//		    }
//		 catch (NameNotFoundException e) {
//		} catch (NoSuchAlgorithmException e) {
//		}

		
		mUiLifecycleHelper = new UiLifecycleHelper(this, mCallback);
		mUiLifecycleHelper.onCreate(savedInstanceState);
		
		mCustomLogin = new CustomLogin(this);
		
		// Check for an incoming notification. Save the info
        Uri intentUri = getIntent().getData();
        if (intentUri != null) {
        	String requestIdParam = intentUri.getQueryParameter("request_ids");
            if (requestIdParam != null) {
            	String array[] = requestIdParam.split(",");
                mRequestId = array[0];
            }
        }
        
        if (savedInstanceState != null) {
			pendingPublishReauthorization = savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
		}
	}

	@Override
	protected void onStart() {
//		if (null != controller) {
//			controller.resumeRefresh();
//		}
		super.onStart();
		if (dialog != null) {
			showDialogWithoutNotificationBar(dialogAction, dialogParams);
		}
	}
	
	@Override
	protected void onStop() {
//		if (null != controller) {
//			controller.stopRefresh();
//		}
		super.onStop();
		if (dialog != null) {
			dialog.dismiss();
		}
	}
	
	@Override
	protected void onResume() {
		GameCenter.isNetworkAvailable = AndroidHelper.isNetworkAvailable(this);
		
		super.onResume();
		
		isPause = false;
		dismissProgressDialog();
		mUiLifecycleHelper.onResume();	
	}	
		
	@Override
	protected void onPause() {
		super.onPause();
		isPause = true;
		mUiLifecycleHelper.onPause();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
        outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
        mUiLifecycleHelper.onSaveInstanceState(outState);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if (requestCode == VservManager.REQUEST_CODE) {
			if (intent != null) {

				if (intent.hasExtra("showAt")
						&& intent.getStringExtra("showAt").equalsIgnoreCase(
								"end")) {

					VservManager.release(this);
					super.finish();
				}
			} else {

				super.finish();
			}
		}
		mUiLifecycleHelper.onActivityResult(requestCode, resultCode, intent);		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mUiLifecycleHelper.onDestroy();
	}

	@Override
	public ViewGroup initView() {		
		setContentView(R.layout.main_layout);
	    return (RelativeLayout) findViewById(R.id.root_view);
	}

	@Override
	public FrameLayout initGameView() {
		return (FrameLayout) findViewById(R.id.game_view);
	}
	
	@Override
	public FrameLayout initAdViewLayout() {
		return (FrameLayout) findViewById(R.id.admob_view);
	}
	
	@Override
	public AndroidApplicationConfiguration config() {
		final AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
		config.useGL20 = true;
		config.useWakelock = true;
		return config;
	}
	
	@Override
	public AndroidGameController initController() {
		return new OAnQuanController(this, this);
	}

	@Override
	public int maxInput() {
		return 13;
	}
	
	@Override
	public boolean isKeyBoard() {
		return GameCenter.isKeyboard;
	}

	@Override
	public int keyboardLayoutId() {
		return R.layout.keyboard_layout;
	}

	@Override
	public int editTextId() {
		return R.id.edit;
	}
    
	@Override
	public String initAppPackage() {
		return "oanquan";
	}

	@Override
	public String initPrefName() {
		return "data";
	}
	
	//************************ FACEBOOK LISTENER ************************//
	
	@Override
	public void onLogin(final IFacebookProcessorListener processorListener) {
		mFBProcessorListener = processorListener;
		mAction = IFacebookProcessorListener.LOGIN;
		handler.post(new Runnable() {
			
			@Override
			public void run() {
				mCustomLogin.onClick();
			}
		});
	}

	@Override
	public void onSendRequest(IFacebookProcessorListener processorListener, final String link, final String message, final String data, final boolean isFilter) {
		mAction = IFacebookProcessorListener.SEND_REQUEST;
		mFBProcessorListener = processorListener;
		handler.post(new Runnable() {
			
			@Override
			public void run() {
				if (isFilter) {
					sendFilteredRequest(link, message, data);
				} else {
					sendRequestDialog(link, message, data);
				}
			}
		});
	}

	@Override
	public void onOpenAction(IFacebookProcessorListener processorListener, final Bitmap image) {
		mAction = IFacebookProcessorListener.PUBLISH_STORY;
		mFBProcessorListener = processorListener;
		handler.post(new Runnable() {
			
			@Override
			public void run() {
				publishStory();
			}
		});
	}
	
	//************************ APPOTA PAYMENT LISTENER ************************//

	//************************ GOOGLE AD LISTENER ************************//

	//************************ VservSea AD ************************************//
	
//	public void showBannerVservseaAd() {
//		if (null != controller) {
//			controller.stopRefresh();
//			controller = null;
//		}
//		if (null != adView) {
//			adView.removeAllViews();
//		}
//		manager = VservManager.getInstance(MainActivity.this);
//
//		manager.getAd(BANNER_ZONE, AdOrientation.LANDSCAPE,
//				new AdLoadCallback() {
//
//					@Override
//					public void onLoadSuccess(VservAd adObj) {
//						Toast.makeText(MainActivity.this, "Success in getting Ad", Toast.LENGTH_SHORT).show();
//						adObject = adObj;
//						if (null != adView) {
//							adView.removeAllViews();
//						}
//						/****************************** APPLICABLE IF USED RENDER AD FUNCTIONALITY ****************************/
//						if (null != controller) {
//							controller.stopRefresh();
//							controller = null;
//						}
//
//						if (null != adObject) {
//							try {
//								adObject.show(MainActivity.this, adView);
//							} catch (ViewNotEmptyException e) {
//								onShowToast(e.getMessage(), SHORT_SHOW);
//								e.printStackTrace();
//							}
//						}
//					}
//
//					@Override
//					public void onLoadFailure() {
//						onShowToast("Failed in getting AD", SHORT_SHOW);
//					}
//
//					@Override
//					public void onNoFill() {
//						onShowToast("No Ad Found", SHORT_SHOW);
//					}
//				});
//	}
//	
	// ===========================================================
	// Methods
	// ===========================================================
	
	//************************ GOOGLE AD PROCESS ************************//
	//************************ FACEBOOK PROCESS ************************//
	
	
	
	void log(final String message) {
		Log.e("MainActivity", message);
	}
	
	public boolean isLogin() {
		return mCustomLogin.isOpenSession();
	}
	
	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
		if (state.isOpened() && mRequestId != null) {
    		getRequestData(mRequestId);
    		mRequestId = null;
    	}
		
	    if (state.isOpened()) {
        	onUpdateView(true);
	    	
            if (pendingPublishReauthorization && state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
            	pendingPublishReauthorization = false;
            	publishStory();
            } else if (dialogParams != null) {
            	if (isSessionOpened) {
        			isSessionOpened = false;
        			if (dialogParams != null) {
        				showDialogWithoutNotificationBar(dialogAction, dialogParams);
        			}
        		}
            }
	    } else if (state.isClosed()) {
	    	onUpdateView(false);
	    }
	    
	}	
	
	private void onUpdateView(final boolean flag) {
		if (flag) {
			if (mFBProcessorListener != null && mAction == IFacebookProcessorListener.LOGIN) {
				mFBProcessorListener.onComplete("");
				mFBProcessorListener = null;
			}
		} else {
			if (mFBProcessorListener != null && mAction == IFacebookProcessorListener.LOGIN) {
				mFBProcessorListener.onFailure("");
				mFBProcessorListener = null;
			}
		}
	}
	
	/*
	 * Helper method to check a collection for a string.
	 */
	private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
	    for (String string : subset) {
	        if (!superset.contains(string)) {
	            return false;
	        }
	    }
	    return true;
	}
	
	/*
	 * Helper method to dismiss the progress dialog.
	 */
	private void dismissProgressDialog() {
		// Dismiss the progress dialog
		if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
	}
	
	/*
	 * Method to publish a story.
	 */
	private void publishStory() {
		// Un-comment the line below to turn on debugging of requests
//		Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);
		
	    Session session = Session.getActiveSession();
	    if (session != null) {
//		    Log.e("Session", "Session != null");
		    // Check for publish permissions    
		    List<String> permissions = session.getPermissions();
		    if (!isSubsetOf(PERMISSIONS, permissions)) {
		    	pendingPublishReauthorization = true;
		    	Session.NewPermissionsRequest newPermissionsRequest = new Session 
		    	.NewPermissionsRequest(this, PERMISSIONS);
		    	session.requestNewPublishPermissions(newPermissionsRequest);
		    	return;
		    }
		    
//		    Log.e("Session", "Session had permission");
		    
		    // Show a progress dialog because the batch request could take a while.
	        progressDialog = ProgressDialog.show(MainActivity.this, "", MainActivity.this.getResources().getString(R.string.progress_dialog_sharing_text), true);
	        
		    try {
				// Create a batch request, firstly to post a new object and
				// secondly to publish the action with the new object's id.
				RequestBatch requestBatch = new RequestBatch();
				
				// Request: Staging image upload request
				// --------------------------------------------
				
				// If uploading an image, set up the first batch request
				// to do this.
				if (UPLOAD_IMAGE) {
					// Set up image upload request parameters
					Bundle imageParams = new Bundle();
					Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher);
					imageParams.putParcelable("file", image);
					
					// Set up the image upload request callback
				    Request.Callback imageCallback = new Request.Callback() {

						@Override
						public void onCompleted(Response response) {
							// Log any response error
							FacebookRequestError error = response.getError();
							if (error != null) {
								dismissProgressDialog();
//								Log.i(TAG, error.getErrorMessage());
							}
						}
				    };
				    
				    // Create the request for the image upload
					Request imageRequest = new Request(Session.getActiveSession(), "me/staging_resources", imageParams, 
			                HttpMethod.POST, imageCallback);
					
					// Set the batch name so you can refer to the result
					// in the follow-on object creation request
					imageRequest.setBatchEntryName("imageUpload");
					
					// Add the request to the batch
					requestBatch.add(imageRequest);
					
				}
								
				// Request: Object request
				// --------------------------------------------
				
		    	// Set up the JSON representing the book
				JSONObject book = new JSONObject();
				
				// Set up the book image
				if (UPLOAD_IMAGE) {
					// Set the book's image from the "uri" result from 
					// the previous batch request
					book.put("image", "{result=imageUpload:$.uri}");
				} else {
					// Set the book's image from a URL
					book.put("image", "http://farm4.staticflickr.com/3667/10670849985_85d29674a1_o.png");
				}				
				book.put("title", "Picture");			
				book.put("url", "http://zegome.com/");
				book.put("description", "Một sự sáng tạo thú vị của tôi");
				
				// Set up object request parameters
				Bundle objectParams = new Bundle();
				objectParams.putString("object", book.toString());
				// Set up the object request callback
			    Request.Callback objectCallback = new Request.Callback() {

					@Override
					public void onCompleted(Response response) {
						// Log any response error
						FacebookRequestError error = response.getError();
						if (error != null) {
							dismissProgressDialog();
							Log.i(TAG, error.getErrorMessage());
						}
					}
			    };
			    
			    // Create the request for object creation
				Request objectRequest = new Request(Session.getActiveSession(), 
						"me/objects/gome_story:picture", objectParams, 
		                HttpMethod.POST, objectCallback);
				
				// Set the batch name so you can refer to the result
				// in the follow-on publish action request
				objectRequest.setBatchEntryName("objectCreate");
				
				// Add the request to the batch
				requestBatch.add(objectRequest);
				
				// Request: Publish action request
				// --------------------------------------------
				Bundle actionParams = new Bundle();
				// Refer to the "id" in the result from the previous batch request
				actionParams.putString("picture", "{result=objectCreate:$.id}");
				// Turn on the explicit share flag
				actionParams.putString("fb:explicitly_shared", "true");
				
				// Set up the action request callback
				Request.Callback actionCallback = new Request.Callback() {

					@Override
					public void onCompleted(Response response) {
						dismissProgressDialog();
						FacebookRequestError error = response.getError();
						if (error != null) {
							Toast.makeText(MainActivity.this
								.getApplicationContext(),
								error.getErrorMessage(),
								Toast.LENGTH_LONG).show();
						} else {
							String actionId = null;
							try {
								JSONObject graphResponse = response
				                .getGraphObject()
				                .getInnerJSONObject();
								actionId = graphResponse.getString("id");
							} catch (JSONException e) {
								Log.i(TAG, "JSON error "+ e.getMessage());
							}
							Toast.makeText(MainActivity.this.getApplicationContext(), actionId,
								Toast.LENGTH_LONG).show();
						}
					}
				};
				
				// Create the publish action request
				Request actionRequest = new Request(Session.getActiveSession(),
						"me/gome_story:draw", actionParams, HttpMethod.POST, actionCallback);
				
				// Add the request to the batch
				requestBatch.add(actionRequest);
				
				// Execute the batch request
				requestBatch.executeAsync();
				
				if (mFBProcessorListener != null) {
					mFBProcessorListener.onComplete("publish story success");
					mFBProcessorListener = null;
				}
				
			} catch (JSONException e) {
				if (mFBProcessorListener != null) {
					mFBProcessorListener.onFailure("publish story failure");
					mFBProcessorListener = null;
				}
				dismissProgressDialog();
			}
		}
	}
	
	private void sendFilteredRequest(final String link, final String message, final String data) {
		
		// Get a list of the user's friends' names and devices
		final Session session = Session.getActiveSession();
		Request friendDevicesGraphPathRequest = Request.newGraphPathRequest(session, "me/friends", new Request.Callback() {
			@Override
			public void onCompleted(Response response) {
				
				FacebookRequestError error = response.getError();
				if (error != null) {
//					Log.e(FriendSmashApplication.TAG, error.toString());
//					((HomeActivity)getActivity()).handleError(error, false);
				} else if (session == Session.getActiveSession()) {
					if (response != null) {
						// Get the result
						GraphObject graphObject = response.getGraphObject();
						JSONArray dataArray = (JSONArray)graphObject.getProperty("data");
						
						if (dataArray.length() > 0) {
							// Ensure the user has at least one friend ...
							
							// Store the filtered friend ids in the following List
							ArrayList<String> filteredFriendIDs = new ArrayList<String>();
							
							for (int i=0; i<dataArray.length(); i++) {
								JSONObject currentUser = dataArray.optJSONObject(i);
								if (currentUser != null) {
									JSONArray currentUserDevices = currentUser.optJSONArray("devices");
									if (currentUserDevices != null) {
										// The user has at least one (mobile) device logged into Facebook
										for (int j=0; j<currentUserDevices.length(); j++) {
											JSONObject currentUserDevice = currentUserDevices.optJSONObject(j);
											if (currentUserDevice != null) {
												String currentUserDeviceOS = currentUserDevice.optString("os");
												if (currentUserDeviceOS != null) {
													if (currentUserDeviceOS.equals("Android")) {
														filteredFriendIDs.add(currentUser.optString("id"));
													}
												}
											}
										}
									}
								}
							}
							
							// Now we have a list of friends with an Android device, we can send requests to them
					    	Bundle params = new Bundle();
					    	
					    	// Uncomment following link once uploaded on Google Play for deep linking
					    	if (link != null)
					    		params.putString("link", link);
					    	
					    	// We create our parameter dictionary as we did before
					    	if (message != null)
					    		params.putString("message", message);
					    	else
					    		params.putString("message", "Come on, my friend! This game is wonderful.");
					    	   
					    	if (data != null) {
					    		params.putString("data", data);
					    	}
					    	
					    	// Of course, not all of our suggested friends will have Android devices - we need to filter them down
					    	ArrayList<String> validSuggestedFriends = new ArrayList<String>();
		             
		                    // So, we loop through each suggested friend
		                    for (String suggestedFriend : filteredFriendIDs)
		                    {
		                        {
		                            // So we can call them valid
		                        	validSuggestedFriends.add(suggestedFriend);
		                        }
		                    }
		                    params.putString("suggestions", TextUtils.join(",", validSuggestedFriends.toArray(new String[validSuggestedFriends.size()])));
							    	
					    	// Show FBDialog without a notification bar
					    	showDialogWithoutNotificationBar("apprequests", params);
						}
					}
				}
			}
		});
		// Pass in the fields as extra parameters, then execute the Request
		Bundle extraParamsBundle = new Bundle();
		extraParamsBundle.putString("fields", "name,devices");
		friendDevicesGraphPathRequest.setParameters(extraParamsBundle);
		Request.executeBatchAsync(friendDevicesGraphPathRequest);
	}
	
	private void sendRequestDialog(final String link, final String message, final String data) {
		Bundle params = new Bundle();
	    params.putString("message", "Learn how to make your Android apps social");

	    showDialogWithoutNotificationBar("apprequests", params);
	}
	
	private void getRequestData(final String inRequestId) {
    	// Create a new request for an HTTP GET with the
    	// request ID as the Graph path.
    	Request request = new Request(Session.getActiveSession(), 
    			inRequestId, null, HttpMethod.GET, new Request.Callback() {
					
					@Override
					public void onCompleted(Response response) {
						// Process the returned response
						GraphObject graphObject = response.getGraphObject();
						FacebookRequestError error = response.getError();
	                    boolean processError = false;
	                    // Default message
	                    String message = "Incoming request";
	                    if (graphObject != null) {
	                    	// Check if there is extra data
	                    	if (graphObject.getProperty("data") != null) {
	                    		try {
	                    			// Get the data, parse info to get the key/value info
	                    			JSONObject dataObject = new JSONObject((String)graphObject.getProperty("data"));
	                    			// Get the value for the key - badge_of_awesomeness
	                    			String badge = dataObject.getString("badge_of_awesomeness");
	                    			// Get the value for the key - social_karma
	                                String karma = dataObject.getString("social_karma");
	                                // Get the sender's name
	                                JSONObject fromObject = (JSONObject) graphObject.getProperty("from");
	                                String sender = fromObject.getString("name");
	                                String title = sender+" sent you a gift";
	                                // Create the text for the alert based on the sender
	                                // and the data
	                                message = title + "\n\n" +  "Badge: "+ badge + " Karma: "+karma;
	                    		} catch (JSONException e) {
	                    			processError = true;
	                    			message = "Error getting request info";
	                    		}
	                    	} else if (error != null) {
	                    		processError = true;
	                    		message = "Error getting request info";
	                    	}
	                    }
	                    Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
	                    if (!processError) {
	                    	deleteRequest(inRequestId);
	                    }

					}
				});
    	// Execute the request asynchronously.
    	Request.executeBatchAsync(request);
    }
	
    private void deleteRequest(String inRequestId) {
    	// Create a new request for an HTTP delete with the
    	// request ID as the Graph path.
    	Request request = new Request(Session.getActiveSession(), 
    			inRequestId, null, HttpMethod.DELETE, new Request.Callback() {
					
					@Override
					public void onCompleted(Response response) {
						// Show a confirmation of the deletion
						// when the API call completes successfully.
						Toast.makeText(MainActivity.this, "Request deleted",
		                        Toast.LENGTH_SHORT).show();
					}
				});
    	// Execute the request asynchronously.
    	Request.executeBatchAsync(request);
    }

	private void showDialogWithoutNotificationBar(final String action, final Bundle params) {
		// Create the dialog
		
		if (params == null) {
			Log.e("params", "fsdfsofnsodnfosdnfds");
			return;
		}
		handler.post(new Runnable() {

			@Override
			public void run() {
				dialog = new WebDialog.Builder(MainActivity.this, Session.getActiveSession(), action, params)
						.setOnCompleteListener(new WebDialog.OnCompleteListener() {

									@Override
									public void onComplete(Bundle values, FacebookException error) {
										if (error != null) {
											if (error instanceof FacebookOperationCanceledException) {
												onShowToast("FacebookOperationCanceledException", SHORT_SHOW);
											} else {
												showError(getResources().getString(R.string.network_error), false);
											}
											if (mFBProcessorListener != null) {
												onShowToast("Failure", SHORT_SHOW);
		        								mFBProcessorListener.onFailure(action + "failure");
		        								mFBProcessorListener = null;
		        							}
										} else {
											if (mFBProcessorListener != null) {
												onShowToast("complete", SHORT_SHOW);
		        								mFBProcessorListener.onComplete(action + "complete");
		        								mFBProcessorListener = null;
		        							}
										}
										
										dialog = null;
										dialogAction = null;
										dialogParams = null;
									}
								}).build();

				// Store the dialog information in attributes
				dialogAction = action;

				// Show the dialog
				dialog.show();
				
				
			}
		});

	}

	// Show user error message as a toast
	private void showError(String error, boolean logout) {
		Toast.makeText(this, error, Toast.LENGTH_LONG).show();
		if (logout) {
			logout();
		}
	}

	
    void handleError(FacebookRequestError error, boolean logout) {
        DialogInterface.OnClickListener listener = null;
        String dialogBody = null;

        if (error == null) {
            dialogBody = getString(R.string.error_dialog_default_text);
        } else {
            switch (error.getCategory()) {

                case AUTHENTICATION_REOPEN_SESSION:
                    // close the session and reopen it.
                    dialogBody = getString(R.string.error_authentication_reopen);
                    listener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Session session = Session.getActiveSession();
                            if (session != null && !session.isClosed()) {
                                session.closeAndClearTokenInformation();
                            }
                        }
                    };
                    break;

                case SERVER:
                case THROTTLING:
                    // this is usually temporary, don't clear the fields, and
                    // ask the user to try again
                    dialogBody = getString(R.string.error_server);
                    break;

                case BAD_REQUEST:
                    // this is likely a coding error, ask the user to file a bug
                    dialogBody = getString(R.string.error_bad_request, error.getErrorMessage());
                    break;

                case CLIENT:
                	// this is likely an IO error, so tell the user they have a network issue
                	dialogBody = getString(R.string.network_error);
                    break;
                    
                case OTHER:
                default:
                    // an unknown issue occurred, this could be a code error, or
                    // a server side issue, log the issue, and either ask the
                    // user to retry, or file a bug
                    dialogBody = getString(R.string.error_unknown, error.getErrorMessage());
                    break;
            }
        }

        new AlertDialog.Builder(this)
                .setPositiveButton(R.string.error_dialog_button_text, listener)
                .setTitle(R.string.error_dialog_title)
                .setMessage(dialogBody)
                .show();
        
        if (logout) {
        	logout();
        }
    }
	
	
	private void logout() {
		Session.getActiveSession().closeAndClearTokenInformation();
	}

	private boolean ensureOpenSession() {
		if (Session.getActiveSession() == null || !Session.getActiveSession().isOpened()) {
			
			Session.openActiveSession(this, true, new Session.StatusCallback() {
				@Override
				public void call(Session session, SessionState state, Exception exception) {
					
					onSessionStateChange(session, state, exception);
				}
			});
			return false;
		}
		return true;
	}

	@Override
	public void onNewsFeed(IFacebookProcessorListener processorListener, String link, String name, String caption, String descript, String pictureUrl) {
		final Bundle params = new Bundle();
		params.putString("name", name);
		params.putString("message", "GomeStory");
		params.putString("caption", caption);
		params.putString("description", descript);
		params.putString("link", link);
		params.putString("picture", pictureUrl);
		
		dialogParams = params;
		if (ensureOpenSession()) {
			showDialogWithoutNotificationBar("feed", dialogParams);
		} else {
			isSessionOpened = true;
		}
	
	}
	// Parameters of a WebDialog that should be displayed
	private WebDialog dialog = null;
	private String dialogAction = null;
	private Bundle dialogParams = null;
	private boolean isSessionOpened = false;

	@Override
	public int id() {
		return ID;
	}

	@Override
	public int chanel() {
		return GOOGLE;
	}

	//************************ APPOTA PAYMENT PROCESS ************************//

}